#include "tim2x.h"

void PWM_Init(u16 Period, u16 Prescaler)
{
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);      //开启GPIOA时钟
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO, ENABLE);       //开始复用时钟
    RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);

    GPIO_InitTypeDef GPIO_InitStructure;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;            //复用推挽输出
    GPIO_InitStructure.GPIO_Pin = CH2;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;

    GPIO_Init(GPIO_PORT, &GPIO_InitStructure);

    TIM_TimeBaseInitTypeDef TIM_InitStructure;
    TIM_InitStructure.TIM_ClockDivision = TIM_CKD_DIV1;    //时钟分割
    TIM_InitStructure.TIM_Period = Period;
    TIM_InitStructure.TIM_Prescaler = Prescaler;
    TIM_InitStructure.TIM_CounterMode = TIM_CounterMode_Up;    //向上计数
    TIM_InitStructure.TIM_RepetitionCounter = DISABLE; //重复计数次数

    TIM_TimeBaseInit(TIM2, &TIM_InitStructure);
    TIM_Cmd(TIM2, ENABLE);

    TIM_OCInitTypeDef PWM_InitStructure;

    PWM_InitStructure.TIM_OCMode = TIM_OCMode_PWM2;
    PWM_InitStructure.TIM_OCPolarity = TIM_OCPolarity_High;
    PWM_InitStructure.TIM_OutputState = TIM_OutputState_Enable;
    TIM_OC2Init(TIM2, &PWM_InitStructure);

    TIM_OC2PreloadConfig(TIM2, ENABLE);    //预装载寄存器
    TIM_SetCompare2(TIM2, 0);

}
